import dayjs from "../../libs/dayjs";
import { Pages } from "../to/pages/Pages";
import { R } from "../to/pages/R";
import { router } from "../to/pages/routerVisitor";
import { toLiveDetail } from "../to/toLiveDetail";
import { toRedPacket } from "../to/toRedPacket";
import { toShare } from "../to/toShare";
import { getSafeClip } from "./getSafeClip";
import { httpPost } from "./httpPost";
import { addMaxFail, setMaxFail } from "./maxFail";
import { parseShareLink } from "./parseShareLink";
import { useDeviceUuid } from "./useDeviceUuid";
import { RedPacketType, useSetting } from "./useSetting";
import { useStorage } from "./useStorage";
const storage = useStorage()
export interface CacheData<T> {
    data: T;
    expire: number;
}
export interface RedPacket {
    name: string,
    link: string,
    online: number,
    openTime: string,
    count: number,
    type: RedPacketType,
    userId: string,
    ksid: string
}
export class RedCache {
    cache: CacheData<RedPacket>[] = []
    put(msg: CacheData<RedPacket>) {
        this.cache.push(msg)
    }
    get(min: number, max: number) {
        const list = this.cache.sort((a, b) => a.expire - b.expire).filter(it => {
            if (it.data.online === 0) return false;
            return it.data.count / it.data.online > 0.4
        }).filter(it => {
            const redPacket = it.data;
            const openTime = dayjs(redPacket.openTime).toDate().getTime()
            const nowTime = dayjs().toDate().getTime()
            const decTime = openTime - nowTime
            if (decTime > max * 1000) {
                return false;
            }
            if (decTime < min * 1000) {
                return false;
            }
            return true;
        }).sort((a, b) => b.data.count / b.data.online - a.data.count / a.data.online)
        if (list.length > 0) return list[0]
        return;
    }
    del(data: CacheData<RedPacket>) {
        try {
            this.cache = [
                ...this.cache
            ].filter(it => it.data.userId !== data.data.userId)
        } catch (e) { }
    }
}
export const redCache = new RedCache()
let time: number = 0;
export function updateRoomInfo() {
    time += 1;
    try {
        // 进入的时候还有30s
        const info = httpPost('kwai/getRoomInfo', {})
        if (info) {
            const userId = info.userId || info.user_id
            time = 0;
            app.startActivity({
                action: 'VIEW',
                data: `kwai://live/play/~${userId}`
            })
            sleep(5000)
            let start = Date.now()
            while (true) {
                const ctx = router.getCurrentContext()
                if (!ctx.isPage(Pages.live)) {
                    toLiveDetail()
                    if (!ctx.isPage(Pages.live)) {
                        events.emit('log', `已离开直播间`)
                        sleep(1000)
                        break;
                    }
                }
                const room = ctx.all()
                if (room.online > 0) {
                    let activities: any[] = ctx.get<any[]>('activities') || []
                    let roomRedPacketInfo = activities.find(it => it.openRedPacket)
                    if (roomRedPacketInfo) {
                        const openTime = roomRedPacketInfo.openTime;
                        if (openTime) {
                            const redOpenTime = dayjs(openTime).toDate().getTime()
                            const nowTime = dayjs().toDate().getTime()
                            const decTime = redOpenTime - nowTime
                            if (decTime > 60 * 10000) {
                                httpPost('kwai/removeRoomInfo', info)
                                events.emit('log', `时间过长`)
                                sleep(1000)
                                break;
                            }
                            if (decTime > 10 * 1000) {
                                info.online = room.online || info.online;
                                events.emit('log', `[${userId}]更新房间 ${info.count}/${info.online}`)
                                const res = httpPost('kwai/updateRoomInfo', info)
                                if (!res) {
                                    events.emit('log', `已被消耗`)
                                    sleep(1000)
                                    break;
                                }
                                if ((info.count / room.online) < 0.6 && decTime > 20 * 1000) {
                                    events.emit('log', `收益率低于0.6 ${info.count}/${room.online}`)
                                    sleep(1000)
                                    httpPost('kwai/removeRoomInfo', info)
                                    break;
                                }
                            } else {
                                events.emit('log', '开包时间小于10s')
                                sleep(1000)
                                break;
                            }
                        } else {
                            events.emit('log', '没有找到开包时间')
                            sleep(1000)
                            break;
                        }
                    } else {
                        if ((Date.now() - start) > 10 * 1000) {
                            httpPost('kwai/removeRoomInfo', info)
                            events.emit('log', '暂无红包')
                            sleep(1000)
                            break;
                        }
                    }
                }
                sleep(1000)
            }
            return true;
        } else {
            events.emit(`log`, `[${time}]暂无房间`)
            sleep(1000)
        }
        return false;
    } catch (e) {
        return false;
    }
}
export function parseRoomInfo() {
    let liveRoomCtx = toLiveDetail()
    let activities: any[] = liveRoomCtx.get<any[]>('activities') || []
    if (activities.length === 0) {
        addMaxFail()
        return false;
    }
    if (!liveRoomCtx.isPage(Pages.live)) {
        addMaxFail()
        return false;
    }
    if (activities && activities.length > 0) {
        let roomRedPacketInfo = activities.find(it => it.openRedPacket)
        const startDate = Date.now()
        while (!roomRedPacketInfo && Date.now() - startDate < 1000 * 5) {
            liveRoomCtx = router.getCurrentContext()
            activities = liveRoomCtx.get<any[]>('activities') || []
            roomRedPacketInfo = activities.find(it => it.openRedPacket)
            sleep(1000)
        }
        if (!roomRedPacketInfo) {
            addMaxFail()
            return false;
        }
        setMaxFail(0)
        roomRedPacketInfo.openRedPacket()
        sleep(2000)
        const redLoading = selector().idEndsWith(R.action_view).findOnce()
        if (!redLoading) {
            events.emit('log', `红包加载超时`)
            addMaxFail()
            return false;
        }
        const redPacketCtx = toRedPacket()
        if (!redPacketCtx.isPage(Pages.redPacket)) {
            addMaxFail()
            return false;
        }
        const redPacketInfo = redPacketCtx.all()
        if (redPacketInfo.close) {
            redPacketInfo.close()
        }
        // 判断是否需要获取分享连接
        const redsList = redPacketInfo.redsList as any[] || [];
        if (redsList.length === 0) {
            addMaxFail()
            return false;
        }
        if (redsList && redsList.length > 0) {
            // setting
            const setting = useSetting()
            if (setting.type && setting.type.length > 0) {
                const red = redsList.find(red => setting.type.includes(red.type))
                if (red) {
                    events.emit('log', '获取分享连接')
                    const shareContext = toShare()
                    if (!shareContext.isPage(Pages.share)) {
                        addMaxFail()
                        return false;
                    }
                    const list = shareContext.get<any[]>('list')
                    if (list && list.length > 0) {
                        const item = list.find(it => it.title === '复制链接')
                        if (item) {
                            item.click()
                            sleep(1000)
                            const link = getSafeClip()
                            if (!link) {
                                events.emit('log', "获取分享链接失败")
                                return false;
                            }
                            const res = link.match(/(http.*?) (.*?)的直播/)
                            if (res && res.length > 0) {
                                const [, link, name] = res
                                const share = parseShareLink(link, name)
                                if (Object.keys(share).length === 0) {
                                    events.emit('log', "分享连接解析失败")
                                    return false
                                }
                                // 上传红包到服务器
                                try {
                                    const roomInfo = router.getCurrentContext().all()
                                    // const redsList = redPacketInfo.redsList as any[];
                                    // 上传红包信息
                                    // try {
                                    //     const reward = red.reward || red;
                                    //     const redInfo: RedPacket = {
                                    //         name: name,
                                    //         link: link,
                                    //         online: roomInfo.online || 0,
                                    //         openTime: roomRedPacketInfo.openTime || "",
                                    //         count: reward.count || reward.total || 0,
                                    //         type: red.type,
                                    //         userId: share.userId,
                                    //         ksid: share.ksid
                                    //     }
                                    //     httpPost('kwai/addRoomInfo', redInfo)
                                    // } catch (e) {
                                    //     console.log(`${(e as any).toString()}`)
                                    // }
                                    const postData = {
                                        link: link,
                                        name: name,
                                        openTime: roomRedPacketInfo.openTime || "",
                                        online: roomInfo.online || 0,
                                        redPacketCount: roomInfo.redPacketCount || 0,
                                        category: roomInfo.category || "",
                                        rank: roomInfo.rank || "",
                                        uuid: useDeviceUuid(),
                                        ...(share || {}),
                                        redPackets: redsList.map(red => {
                                            const reward = red.reward || red;
                                            return {
                                                type: red.type,
                                                count: reward.count,
                                                total: reward.total || 0,
                                                text: red.desc,
                                                password: red.password || "",
                                                unit: reward.unit,
                                                sub_title: "",
                                                title: red.desc,
                                                desc: red.condiction
                                            }
                                        })
                                    }
                                    events.emit('log', `提交红包`)
                                    httpPost("addRedPkg", postData)
                                    return true;
                                } catch (e) {
                                    events.emit('log', '提交失败' + (e as any).toString())
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return false;
}